package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
	"github.com/lab-online/pkg/util"
)

type importStudentReqDataItem struct {
	Name     string `json:"name" binding:"required,max=16" example:"杏鸣"`                 // 姓名
	Username string `json:"username" binding:"required,max=10,min=3" example:"20240126"` // 学号
	Password string `json:"password" binding:"required,max=64,min=8" example:"12345678"` // 密码
}

type ImportStudentReqBody = []importStudentReqDataItem

var ImportStudentValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Body: &ImportStudentReqBody{},
	}
})

type importStudentRespBodyDataItem = updateUserRespBodyData

type ImportStudentRespBody struct {
	resp.BaseRespBody
	Data []*importStudentRespBodyDataItem `json:"data" binding:"required"`
}

// ImportStudent
//
//	@Summary				导入学生
//	@Description.markdown	ImportStudent
//	@Tags					user
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string					true	"`Teacher` | `Admin`"
//	@Param					Body			body		ImportStudentReqBody	true	"JSON 请求体"
//	@Success				200				{object}	ImportStudentRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@Router					/v1/users/import [post]
func (h *Handler) ImportStudent(c *gin.Context) {
	users := c.MustGet(mw.KeyBody).(*ImportStudentReqBody)

	userEntities := util.SliceMap(*users,
		func(user importStudentReqDataItem) entity.UserEntity {
			return entity.NewUserEntity(
				entity.WithName(user.Name),
				entity.WithUsername(user.Username),
				entity.WithPassword(user.Password),
			)
		})

	if savedUsers, err := h.domain.ImportStudent(userEntities); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Created(c, constant.CodeSuccessImport, util.SliceMap(savedUsers,
			func(user entity.UserEntity) *importStudentRespBodyDataItem {
				return &importStudentRespBodyDataItem{
					Username: user.GetUsername(),
					Name:     user.GetName(),
					Role:     user.GetRole(),
				}
			}))
	}
}
